<script setup>
import { inject, nextTick, ref } from "vue";
import { addressListApi, userCityApi } from "@/services/address";
import { onLoad, onShow } from "@dcloudio/uni-app";
import { useaddressStore } from "@/stores/address";
import tabbarView from "../components/tabbar.vue";
// import { QQMapWX } from "./qqmap-wx-jssdk.js";

const valuetabbar = ref(1);

const dateobj = useaddressStore();
const type = ref(null);
const lat = ref("");
const lng = ref("");
const keyword = ref("");
const code = ref("");
const cityname = ref("");
const citycode = ref("");

const addAddress = () => {
  uni.navigateTo({
    url: "/pages/address_add/index",
  });
};
const qqmapsdk = ref(null);

onLoad((e) => {
  type.value = e.type ? e.type : null;
  if (uni.getStorageSync("citycode")) {
    uni.removeStorageSync("citycode");
  }
  // qqmapsdk.value = new QQMapWX({
  //   key: "DC2BZ-NLEL7-LGDX5-PJZRB-NAFA2-F7B2T",
  // });
});
onShow(() => {
  console.log("sdasdasd");
  // uni.setStorageSync("cityname", res.data.city);
  // uni.setStorageSync("citycode", res.data.code);
  if (uni.getStorageSync("cityname")) {
    cityname.value = uni.getStorageSync("cityname");
    citycode.value = uni.getStorageSync("citycode");
  } else {
    citycode.value = "";
    cityname.value = uni.getStorageSync("getcityname")
      ? uni.getStorageSync("getcityname")
      : "";
  }
  nextTick(() => {
    console.log("cityname", uni.getStorageSync("cityname"));
  });

  valuetabbar.value = 1;
  //#ifdef MP-WEIXIN
  // addressListFun();
  uni.authorize({
    scope: "scope.userLocation",
    success() {
      // 用户已经同意小程序使用定位功能

      uni.getLocation({
        type: "wgs84", // 返回可以用于uni.openLocation的经纬度，默认为wgs84的gps坐标
        success: function (res) {
          console.log("当前位置的经度：" + res.longitude);
          console.log("当前位置的纬度：" + res.latitude);
          lat.value = res.latitude;
          lng.value = res.longitude;
          // console.log("QQMapWX", qqmapsdk.value, QQMapWX);
          // //使用jdk的方法解析
          // QQMapWX.reverseGeocoder({
          //   location: [lat.value, lng.value].join(","),
          //   success: function (res) {
          //     console.log("sdaasasa", res.result);
          //   },
          // });
          addressListFun();
          if (!uni.getStorageSync("getcityname")) {
            addressdwFun();
          }
        },
        fail: function (error) {
          lat.value = "";
          lng.value = "";
          addressListFun();

          console.error("获取位置失败：", error);
        },
      });
    },
    fail() {
      // 用户拒绝了小程序使用定位功能的权限
      uni.showModal({
        title: "提示",
        content: "此功能需要获取您的地理位置，请确认授权",
        success: function (modalRes) {
          if (modalRes.confirm) {
            uni.openSetting(); // 引导用户去设置中开启权限
          }
        },
      });
    },
  });

  //#endif

  //#ifndef MP-WEIXIN
  console.log("获取位置");
  // addressListFun();
  // return;
  uni.getLocation({
    type: "wgs84", // 返回可以用于uni.openLocation的经纬度，默认为wgs84的gps坐标
    success: function (res) {
      console.log("当前位置的经度：" + res.longitude);
      console.log("当前位置的纬度：" + res.latitude);
      lat.value = res.latitude;
      lng.value = res.longitude;
      addressListFun();
      if (!uni.getStorageSync("getcityname")) {
        addressdwFun();
      }
    },
    fail: function (error) {
      console.error("获取位置失败：", error);
      lat.value = "";
      lng.value = "";

      addressListFun();
    },
  });
  //#endif
});

const addressdwFun = () => {
  console.log(12321312312);
  if (!lat.value) {
    uni.showToast({
      title: "请到设置允许获取位置",
      icon: "none",
    });
    return;
  }
  userCityApi({ lat: lat.value, lng: lng.value }).then((res) => {
    uni.setStorageSync("getcityname", res.data.city);
    // uni.setStorageSync("citycode", res.data.code);
    cityname.value = res.data.city;

    uni.switchTab({
      url: "/pages/address/index",
    });

    // citylist.value = res.data;
  });
};

const addressData = ref([]);

async function addressListFun() {
  let res = null;
  //发送请求
  if (lat.value) {
    res = await addressListApi({
      page: 1,
      lat: lat.value,
      lng: lng.value,
      keyword: keyword.value,
      code: citycode.value,
    });
  } else {
    res = await addressListApi({ page: 1, keyword: keyword.value });
  }

  addressData.value = res.data;
  if (uni.getStorageSync("cityname")) {
    uni.removeStorageSync("cityname");
    uni.removeStorageSync("citycode");
    // cityname.value = uni.getStorageSync("cityname");
    // citycode.value = uni.getStorageSync("citycode");
  }
}
const search = () => {
  addressListFun();
};

// 编辑
const updateAdderss = (item) => {
  uni.openLocation({
    latitude: Number(item.latitude),
    longitude: Number(item.longitude),
    name: item.address,
    success: function () {
      console.log("success");
    },
  });
  // uni.navigateTo({
  //   url: `/pages/address_add/index?address_id=${address_id}`,
  // });
};

const selectaddress = (item) => {
  // goPageA(JSON.stringify(item));

  if (type.value == "add") {
    dateobj.setaddress(JSON.stringify(item));
    // // 4. 返回上一页面
    uni.navigateBack({
      delta: 1, // 返回的页面数
    });
  }
};
const contphone = (item) => {
  uni.makePhoneCall({
    phoneNumber: item, //仅为示例，并非真实的电话号码
  });
};

const goaddressFun = () => {
  uni.navigateTo({
    url: "/pages/address/city",
  });
};
</script>

<template>
  <view class="content">
    <view class="content-search">
      <view class="content-top-city" v-if="cityname" @click="goaddressFun">
        <text>{{ cityname }}</text>
        <up-icon
          name="arrow-down-fill"
          color="#8C8C8C"
          size="32rpx"
          style="margin-top: 0rpx"
        ></up-icon>
      </view>
      <view class="content-top-city" v-if="!cityname" @click="goaddressFun">
        <text>{{ "去定位" }}</text>
        <up-icon
          name="arrow-right"
          color="#8C8C8C"
          size="32rpx"
          style="margin-top: 0rpx"
        ></up-icon>
      </view>
      <u-search
        placeholder="输入搜索"
        v-model="keyword"
        @search="search"
      ></u-search>
    </view>

    <view
      class="content-list"
      v-show="addressData && addressData.list && addressData.list.length > 0"
    >
      <view
        class="content-list-item"
        v-for="(item, index) in addressData && addressData.list"
        :key="index"
        @tap.stop="selectaddress(item)"
      >
        <view>
          <view class="content-list-imgortext">
            <view class="content-list-img">
              <image :src="item.images[0]" mode="aspectFill"></image>
            </view>
            <view class="content-list-title">
              <view class="content-list-name">
                <view class="content-list-nameorphone">
                  <text>{{ item.shop_name }}</text>
                  <!-- <text>{{ item.address }}</text> -->
                </view>
                <text class="select-item" v-if="item.is_default">默认</text>
              </view>
              <view class="content-list-address">
                <up-icon
                  name="clock"
                  color="#8C8C8C"
                  size="26rpx"
                  style="margin-top: 0rpx"
                ></up-icon>
                营业时间:{{ item.business_hours }}
              </view>
              <view class="content-list-address">
                <up-icon
                  name="map"
                  color="#8C8C8C"
                  size="26rpx"
                  style="margin-top: 0rpx"
                ></up-icon>
                {{ item.address }}
              </view>
            </view>
          </view>
        </view>

        <!-- <view class="content-icon" @tap.stop="updateAdderss(item)">
          <up-icon name="map-fill" color="#8C8C8C" size="48rpx"></up-icon>
        </view> -->
        <view class="content-icon-bt">
          <view class="content-icon-bt-item" @click.stop="contphone(item.phone)"
            ><up-icon
              name="phone"
              color="#01ADA8 "
              size="42rpx"
              style="margin-right: 5rpx; font-weight: bold"
            ></up-icon
            ><text>联系门店</text>
          </view>
          <view
            class="content-icon-bt-item content-icon-bt-item-right"
            @tap.stop="updateAdderss(item)"
            ><up-icon
              name="pushpin"
              color="#01ADA8 "
              size="42rpx"
              style="margin-right: 5rpx; font-weight: bold"
            ></up-icon
            ><text :class="index != 0 ? 'default' : ''"
              >{{ index == 0 ? "距离最近" : item.distance + "公里" }}
            </text></view
          >
        </view>
      </view>
    </view>
    <view
      class="nodate-bt"
      v-if="addressData && addressData.list && addressData.list.length == 0"
    >
      <image src="/static/nodate/datas.png" mode="widthFix"></image>
    </view>

    <!-- <view class="foodr-bt">
      <view class="foodr-bt-k">
        <view class="bt-sbuit" @click.shop="addAddress">
          <up-icon name="plus" color="#FFFFFF" size="28rpx"></up-icon>
          <text class="add-text">选择</text>
        </view>
      </view>
    </view> -->
  </view>
  <!-- #ifdef MP-WEIXIN || WEB  -->
  <tabbarView :value="valuetabbar"></tabbarView>
  <!-- #endif -->
</template>

<style lang="scss" scoped>
@import "./index.scss";
</style>
